<template>
  <div class="card">
    <div class="card-body py-0">
      <nav class="float-end">
        <my-pagination
          :row-count="sc.rowCount"
          :page-total="sc.pageTotal"
          :page-no="sc.pageNo"
          @next-page="nextPage"
          @prev-page="prevPage"
          @direct-page="directPage"
        ></my-pagination>
      </nav>
    </div>
    <table class="table table-striped table-hover table-sm">
      <thead>
        <tr>
          <th>账单号</th>
          <th>客户</th>
          <th>审核状态</th>
          <th>出票日期</th>
          <th class="text-end">账单金额</th>
          <th class="text-end">成本</th>
          <th class="text-end">利润</th>
          <th>备注</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td colspan="4" class="text-end">合计：</td>
          <td class="text-end">{{ totalBillSum }}</td>
          <td class="text-end fw-bold text-danger h4">
            {{ totalCost }}
          </td>
          <td class="text-end">{{ totalProfit }}</td>
          <td></td>
          <td></td>
        </tr>
        <tr v-if="orders.length > 0">
          <td colspan="9">
            <button
              @click.stop="uncheckAll()"
              class="btn btn-sm btn-secondary ms-2"
            >
              全否
            </button>
            <button
              @click.stop="checkAll()"
              class="btn btn-sm btn-primary ms-2"
            >
              全选
            </button>

            <button
              class="btn btn-success float-end"
              @click.stop="reviewPass()"
            >
              审核通过
            </button>
          </td>
        </tr>

        <tr v-for="(info, index) in orders" :key="index">
          <td>
            <input type="checkbox" :value="info.id" v-model="reviewedIds" />
            <router-link
              :to="`/bill/detail/` + info.id + `?print=1`"
              target="_blank"
              >{{ info.billNum }}</router-link
            >
          </td>
          <td>
            <template v-if="info.customerType === 0"> 散客 </template>
            <template v-else-if="info.customer !== null">
              {{ info.customer.vipName }}
              <br />
              {{ info.customer.customerCode }}
            </template>
          </td>
          <td>
            <span v-if="info.audited === '1'">已审</span>
          </td>
          <td>{{ info.etdzDate }}</td>

          <td class="text-end">{{ info.billSum }}</td>
          <td class="text-end">{{ info.cost }}</td>
          <td class="text-end">{{ info.profit }}</td>
          <td>{{ info.remark }}</td>
        </tr>

        <tr>
          <td colspan="4" class="text-end">合计：</td>
          <td class="text-end">{{ totalBillSum }}</td>
          <td class="text-end">{{ totalCost }}</td>
          <td class="text-end">{{ totalProfit }}</td>
          <td></td>
          <td></td>
        </tr>
        <tr v-if="orders.length > 0">
          <td colspan="9">
            <button
              @click.stop="uncheckAll()"
              class="btn btn-sm btn-secondary ms-2"
            >
              全否
            </button>
            <button
              @click.stop="checkAll()"
              class="btn btn-sm btn-primary ms-2"
            >
              全选
            </button>

            <button
              class="btn btn-success float-end"
              @click.stop="reviewPass()"
            >
              审核通过
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <div class="card-footer">
      <nav class="float-end">
        <my-pagination
          :row-count="sc.rowCount"
          :page-total="sc.pageTotal"
          :page-no="sc.pageNo"
          @next-page="nextPage"
          @prev-page="prevPage"
          @direct-page="directPage"
        ></my-pagination>
      </nav>
    </div>

    <my-modal-prompt ref="modalPrompt">
      <span slot="title">{{ modalTitle }}</span>
    </my-modal-prompt>
  </div>
</template>

<script>
import MyPagination from "@/components/my-pagination.vue";
import { searchTpr } from "@/api/flight";
import { reviewBillInfoPassed, searchBills } from "@/api/bill";
import MyModalPrompt from "@/components/modal/my-modal-prompt.vue";

export default {
  components: {
    MyPagination,
    MyModalPrompt,
  },
  props: {
    supplierId: {
      type: Number,
      required: true,
    },
    etdzDate: {
      type: String,
      required: true,
    },
    ticketStatus: {
      type: Number,
      required: true,
    },
    reviewed: {
      type: Number,
      default: -1,
    },
    intlTicket: {
      type: Number,
      default: -1,
    },
    pageSize: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      orders: [],
      sc: {
        rowCount: 0,
        pageNo: 1,
        pageSize: 25,
        pageTotal: 0,
      },
      totalBillSum: 0,
      totalCost: 0,
      totalProfit: 0,

      reviewedIds: [],
      modalTitle: "",
    };
  },
  watch: {
    etdzDate: function () {
      this.search();
    },
    ticketStatus: function () {
      this.search();
    },
    pageSize: function () {
      this.search();
    },
    supplierId: function () {
      this.search();
    },
    reviewed: function () {
      this.search();
    },
    intlTicket: function () {
      this.search();
    },
    reviewedIds: function () {
      console.log("reviewedIds is changed.");
      this.calcTotal();
    },
  },
  mounted: function () {
    this.search();
  },
  methods: {
    showErrMsg: function (msg, msgType) {
      this.$store.dispatch("showAlertMsg", {
        errMsg: msg,
        errMsgType: msgType,
      });
    },
    showLoading: function (loadingText) {
      this.$store.commit("showLoading", {
        loading: true,
        loadingText: loadingText,
      });
    },
    hideLoading: function () {
      this.$store.commit("showLoading", {
        loading: false,
      });
    },
    search: function () {
      if (this.supplierId < 1) {
        return;
      }
      if (this.etdzDate.length === 0) {
        return;
      }
      this.orders.splice(0);
      // this.uncheckAll()
      const params = {
        "sc.pageNo": this.sc.pageNo,
        "sc.pageSize": this.pageSize,
        "sc.etdzDateBegin": this.etdzDate,
        "sc.etdzDateEnd": this.etdzDate,
        "sc.intlTicket": this.intlTicket,
        ticketStatus: this.ticketStatus,
        supplierId: this.supplierId,
        reviewed: this.reviewed,
        billType: "-1",
        customerId: -1,
      };

      this.showLoading();

      searchBills(
        params,
        (jsonResult) => {
          this.orders = jsonResult.dataList;
          this.sc = jsonResult.page;
          this.checkAll();
          this.calcTotal();
        },
        () => {
          this.hideLoading();
        }
      );
    },
    prevPage: function () {
      this.sc.pageNo = this.sc.pageNo - 1;
      if (this.sc.pageNo < 1) this.sc.pageNo = 1;
      this.search();
    },
    nextPage: function () {
      this.sc.pageNo = this.sc.pageNo + 1;
      this.search();
    },
    directPage: function (pageNo) {
      this.sc.pageNo = pageNo;
      this.search();
    },
    resetTotal: function () {
      this.totalBillSum = 0;
      this.totalCost = 0;
      this.totalProfit = 0;
    },
    calcTotal: function () {
      this.resetTotal();

      for (const info of this.orders) {
        if (this.reviewedIds.indexOf(info.id) >= 0) {
          this.totalBillSum += info.billSum;
          this.totalCost += info.cost;
          this.totalProfit += info.profit;
        }
      }

      this.totalBillSum = Math.round(this.totalBillSum * 100) / 100;
      this.totalCost = Math.round(this.totalCost * 100) / 100;
      this.totalProfit = Math.round(this.totalProfit * 100) / 100;
    },
    checkAll: function () {
      const self = this;
      this.reviewedIds = [];
      this.orders.forEach(function (item) {
        self.reviewedIds.push(item.id);
      });
      this.calcTotal();
    },
    uncheckAll: function () {
      this.reviewedIds = [];
      this.resetTotal();
    },
    reviewPass: function () {
      if (this.reviewedIds.length < 1) {
        this.showErrMsg("请选中审核通过的账单号");
        return;
      }

      this.modalTitle = "请确认要通过审核的账单总金额为：";
      this.$refs.modalPrompt
        .modal(this.totalBillSum)
        .then(() => {
          reviewBillInfoPassed(
            {
              total: this.totalBillSum,
              billIds: this.reviewedIds,
            },
            (v) => this.commonShowMessage(v)
          );
        })
        .catch((ex) => {});
    },
    commonShowMessage: function (jsonResult) {
      if (jsonResult.status !== "OK") {
        this.showErrMsg("失败：" + jsonResult.errmsg);
      } else {
        if (jsonResult.desc !== "") {
          this.showErrMsg(jsonResult.desc);
        } else {
          this.showErrMsg("操作成功");
        }
      }
    },
  },
};
</script>